package com.alibaba.cloud.transmit.mq;

import com.alibaba.cloud.transmit.constant.TransmitConstant;
import com.alibaba.framework.wrapper.RedisWrapper;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class DeadLetterListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(DeadLetterListener.class);

    @Autowired
    private RedisWrapper<String, Object> redisWrapper;

    @RabbitListener(queues = TransmitConstant.DEAD_LETTER_QUEUE)
    public void deadLetterReceive(Message message, Channel channel) throws IOException {
        String mess = new String(message.getBody());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String key = TransmitConstant.DEAD_LETTER_QUEUE + ":" + deliveryTag;
        if (redisWrapper.hasKey(key)) {
            LOGGER.info("消息已处理过DeliveryTag：{}", deliveryTag);
            return;
        }
        LOGGER.info("DeliveryTag: {}, 收到死信消息：{}", deliveryTag, mess);
        // 发送告警消息，记录到数据库
        redisWrapper.putValueWithExpireTime(key, mess, 10*60, TimeUnit.SECONDS);
        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();

            channel.basicNack(deliveryTag, false, false);
        }
    }
}
